package com.resou.reader.mine.login;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import com.resou.reader.R;
import com.resou.reader.api.ApiImp;
import com.resou.reader.api.entry.Result;
import com.resou.reader.api.service.UserService;
import com.resou.reader.base.v.BaseActivity;
import com.resou.reader.bookshelf.listener.OnItemClickListener;
import com.resou.reader.mine.IView.UserInstance;
import com.resou.reader.utils.ToastUtil;
import com.resou.reader.utils.log.RsLog;
import com.resou.reader.mine.model.LocalImageAdapter;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class LocalPhotoListActivity extends BaseActivity implements OnItemClickListener {

    private static final int CAMERA_REQUEST_CODE = 1;
    private static final int CROP_REQUEST_CODE = 2;

    @BindView(R.id.local_image_recycler)
    RecyclerView mRecyclerView;
    @BindView(R.id.title_share)
    ImageView mImageView;

    private List<String> mPhotos = new ArrayList<>();

    private LocalImageAdapter mAdapter;

    private File mFile;//调用相机返回图片地址

    private void initViews() {
        mAdapter = new LocalImageAdapter(mPhotos, this);
        mRecyclerView.setAdapter(mAdapter);

        GridLayoutManager glm = new GridLayoutManager(this, 3);
        mRecyclerView.setLayoutManager(glm);
    }

    @Override
    protected void initView() {
        initViews();
        mPhotos.add("");
        Observable<List<String>> observable = Observable.create(new ObservableOnSubscribe<List<String>>() {
            @Override
            public void subscribe(ObservableEmitter<List<String>> emitter) {
                String[] projection = {MediaStore.Images.ImageColumns.DATA, MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME};
                String sortOrder = MediaStore.Images.ImageColumns.DATE_TAKEN + " DESC ";//倒叙查询

                Cursor cursor = getContentResolver().query(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, null, null, sortOrder);
                while (cursor.moveToNext()) {
//                    //获取图片的名称
//                    String name = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME));
//                    获取图片的详细信息
//                    String desc = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DESCRIPTION));
//                    获取图片路径
                    String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                    mPhotos.add(path);
                }
                emitter.onNext(mPhotos);
            }
        });
        observable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<List<String>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(List<String> strings) {
                        RsLog.d("photo size == " + mPhotos.size());
                        mAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onComplete() {
                    }
                });

    }

    @Override
    protected void retryRefreshData() {

    }

    @Override
    protected void initPresenter() {

    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_local_photo_list;
    }

    public static void startActivity(Context context) {
        context.startActivity(new Intent(context, LocalPhotoListActivity.class));
    }

    Uri imageUri;

    @Override
    public void onItemClicked(RecyclerView.Adapter adapter, View itemView, int index) {
        if (index == 0) {
            Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); //系统常量， 启动相机的关键
            startActivityForResult(openCameraIntent, CAMERA_REQUEST_CODE); // 参数常量为自定义的request code, 在取返回结果时有用
//            File file = new File(getCacheDir() + "/" + "temp.jnp");
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//                imageUri = FileProvider.getUriForFile(LocalPhotoListActivity.this, "com.resou.reader", file);//通过FileProvider创建一个content类型的Uri
//            } else {
//                imageUri = Uri.fromFile(file);
//            }
//            Intent intent = new Intent();
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); //添加这一句表示对目标应用临时授权该Uri所代表的文件
//            }
//            intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);//设置Action为拍照
//            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);//将拍取的照片保存到指定URI
//            startActivity(intent, CAMERA_REQUEST_CODE);
        } else {
            ChoicePhotoActivity.startActivity(this, mPhotos.get(index));
        }

    }

    private static final String TAG = "LocalPhotoList-APp";

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.d(TAG, "onActivityResult: ");
        switch (requestCode) {
            case CAMERA_REQUEST_CODE:
                if (resultCode == RESULT_OK) {
//                    cropPhoto();
                }
                break;
            //调用剪裁后返回
            case CROP_REQUEST_CODE:
                Bundle bundle = data.getExtras();
                if (bundle != null) {
                    //在这里获得了剪裁后的Bitmap对象，可以用于上传
                    Bitmap image = bundle.getParcelable("data");
                    //设置到ImageView上
                    mImageView.setImageBitmap(image);
                    //也可以进行一些保存、压缩等操作后上传
                    String path = saveImage("userHeader", image);
                    File file = new File(path);
                    /*
                     *上传文件的额操作
                     */

                }
                break;
        }
    }




    @Override
    public Context getViewContext() {
        return this;
    }

    /**
     * 裁剪图片
     */
    private void cropPhoto() {
        File file = new File(getCacheDir() + "/" + "temp.jnp");
        Uri outputUri = Uri.fromFile(file);
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        intent.setDataAndType(outputUri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, CROP_REQUEST_CODE);
    }

    /**
     * 保存图片到本地
     *
     * @param name
     * @param bmp
     * @return
     */
    public String saveImage(String name, Bitmap bmp) {
        File appDir = new File(Environment.getExternalStorageDirectory().getPath());
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = name + ".jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
            return file.getAbsolutePath();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
